package Controller;
import gui.Form;
import java.util.Timer;
import java.util.TimerTask;

import connection.LightStates;



/**
 * A clock object that updates Moveable objects based on the time that has passed.
 * @author imahilus
 */
public class SimulatorClock extends TimerTask
{
    private Timer time;
    public static final int updatesPerSecond = 5; //may not exceed 1000 due to timing constraints



    @SuppressWarnings("LeakingThisInConstructor")
    public SimulatorClock()
    {
        //create a timer object
        time = new Timer("SimulatorClock Timer", true);
        time.scheduleAtFixedRate(this, 1000, 1000/updatesPerSecond);
    }



    //execute the time based task(s)
    @Override
    public void run()
    {
        //first execute all traffic light state changes, then move all the objects
        char[] crossing = Form.Crossing.getText().toCharArray();
        int[]  state;
        int    x;
        while(!SimulatorController.trafficLightChanges.isEmpty())
        {
            state = SimulatorController.trafficLightChanges.get(0);
            x     = (SimulatorWaypoints.lanes[state[0]].trafficLight[1]*SimulatorWaypoints.lineWidth)+SimulatorWaypoints.lanes[state[0]].trafficLight[0];

            if((state[1] == LightStates.ORANGE)&&(crossing[x] == ' '))
            {
                crossing[x] = '*'; //orange
            }
            else
            if((state[1] == LightStates.GREEN)&&(crossing[x] == SimulatorWaypoints.lanes[state[0]].trafficLightGraphic))
            {
                crossing[x] = ' '; //clear this traffic light (green)
            }
            else
            if((state[1] == LightStates.RED)&&(crossing[x] != SimulatorWaypoints.lanes[state[0]].trafficLightGraphic))
            {
                crossing[x] = SimulatorWaypoints.lanes[state[0]].trafficLightGraphic; //set this traffic light (red, orange)
            }
            Form.Crossing.setText(new String(crossing));
            SimulatorController.trafficLightChanges.remove(0);
        }
        int i = 0;
        SimulatorObject obj;
        for(SimulatorLane lane : SimulatorWaypoints.lanes)
        {
            i = 0;
            while(i < lane.contents.size())
            {
                obj = lane.contents.get(i);
                obj.Move();
                if(obj.mayDelete())
                {
                    lane.contents.remove(obj);
                }
                else
                {
                    i += 1;
                }
            }
        }
    }
}
